﻿(function(configs) {
	$(document).ready(function() {
		chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
			let tab = tabs[0], isOSC = tab.url.includes('oschina') || /开源中国/.test(tab.title)
			
			Vue.config.debug = true;
			let currUrl = tab.url, hostSuffixes = ['.net', '.org', '.com']
				, cusHostUrl = 'zb.oschina'
				, cusHostIP = '192.168.1.32'
				, reHostSuffix = /\.[a-z]+$/i
			var oscUrls = new Vue({
				el: '#osc-urls',
				data: {
					isOSC,
					currUrl,
					cusHostUrl,
					cusHostIP,
					qrText: tab.url
				},
				computed: {
					urls() {
						let currUrlObj = new URL(this.currUrl), isIP = reHostSuffix.test(currUrlObj.hostname), urls
						currUrlObj.protocol = 'http'
						$('#cusHostUrl').attr('disabled', isIP)
						
						if (isIP) { // not ip
							urls = hostSuffixes.map(suffix => (currUrlObj.hostname = currUrlObj.hostname.replace(reHostSuffix, suffix), currUrlObj.href))
							return urls.concat((currUrlObj.host = this.cusHostIP, currUrlObj.href))
						} else { // ip
							urls = hostSuffixes.map(suffix => (currUrlObj.host = this.cusHostUrl+suffix, currUrlObj.href))
							return urls.concat((currUrlObj.host = this.cusHostIP, currUrlObj.href))
						}
					},
					qrcode() {
						$("#qrcodeContainer").empty().qrcode({
							size: 300,
							text: this.qrText || tab.url
						})
					}
				},
				methods: {
					replace(url) {
						chrome.tabs.update(tab.id, { url: url })
						this.currUrl = this.qrText =url
					},
					open(url) {
						chrome.tabs.create({
							url: url,
							windowId: tab.windowId,
							index: tab.index + 1,
							active: true
						})
					},
					copy(evt) {
						$(evt.target).parent().siblings('input').select()
						document.execCommand('copy')
					},
					qr(url) {
						this.qrText = url
					}
				}
			})
		})
	})
})()